#!/bin/bash

echo -e "Installer for tests packs..."

if [ -z $1 ]; then
  echo "Must specify test pack to install!"
  exit 2
fi

PACK=$1

TESTSBRANCH=$2
if [ -z "$TESTSBRANCH" ]; then
  echo "Using branch master..."
  TESTSBRANCH='master'
fi

TESTSREPO='https://github.com/StackStorm/st2tests.git'
TESTSPATH="/opt/stackstorm/packs"
VENVSPATH="/opt/stackstorm/virtualenvs"
TMPPATH='/tmp/st2tests'

if [ -d ${TMPPATH} ]; then
  echo -e "Deleting ${TMPPATH}..."
  rm -Rf ${TMPPATH}
fi

echo -e "Cloning st2tests to ${TMPPATH}..."
git clone -b ${TESTSBRANCH} ${TESTSREPO} ${TMPPATH}

echo -e "Checking if ${PACK} pack is installed..."
CHECK=`st2 action list | grep '${PACK}.' &> /dev/null`

if [ "$?" == 0 ]; then
  echo -e "Uninstalling existing ${PACK} pack..."
    st2 run packs.uninstall packs=${PACK}
fi

if [ -d ${TESTSPATH}/${PACK} ]; then
  echo -e "Deleting ${TESTSPATH}/${PACK}..."
  rm -Rf ${TESTSPATH}/${PACK}
fi

if [ -d ${VENVSPATH}/${PACK} ]; then
  echo -e "Deleting ${VENVSPATH}/${PACK}..."
  rm -Rf ${VENVSPATH}/${PACK}
fi

echo -e "Copying ${PACK} to ${TESTSPATH}..."
cp -Rf ${TMPPATH}/packs/${PACK} ${TESTSPATH}/

echo -e "Reloading St2 content..."
st2ctl reload

echo -e "Bootstrapping virtualenv for ${PACK} pack..."
if [ -f ${TESTSPATH}/${PACK}/requirements.txt ]; then
    echo "Creating virtualenv for ${PACK}..."
    mkdir -p ${VENVSPATH}
    virtualenv ${VENVSPATH}/${PACK}
    echo "Installing requirements.txt for ${PACK}..."
    source ${VENVSPATH}/${PACK}/bin/activate
    pip install -r ${TESTSPATH}/${PACK}/requirements.txt
    deactivate
fi


if [ -d ${TMPPATH} ]; then
  echo -e "Cleaning temporary directory..."
  rm -Rf ${TMPPATH}
fi
